<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="运点类型" prop="type">
        <el-select filterable v-model="queryParams.type" placeholder="请选择运点类型" clearable>
          <!--          0:派送；1:其他-->
          <el-option label="派送" value="0"/>
          <el-option label="其他" value="1"/>
        </el-select>
      </el-form-item>
      <el-form-item label="服务区域" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入服务区域"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['extend:serverZone:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['extend:serverZone:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['extend:serverZone:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['extend:serverZone:export']"
        >导出
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['extend:serverZone:import']"
        >导入配送时效
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-s-platform"
          size="mini"
          @click="handleOtherCost"
        >其他费用
        </el-button>
      </el-col>


      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-s-platform"
          size="mini"
          @click="handleShippingTime"
        >干线费用时效
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="serverZoneList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed/>
      <el-table-column label="服务区域编号" align="center" prop="id" />
      <el-table-column label="运点类型" align="center" prop="type">
        <template #default="scope">
          <span v-if="scope.row.type === 0">派送</span>
          <span v-else>其他</span>
        </template>
      </el-table-column>
      <el-table-column label="组织机构" align="center" prop="jcOrganizationIdDtLabel"/>
      <el-table-column label="服务区域" align="left" prop="jcZonesDtLabel" width="250">
        <template #default="scope">
          <span v-if="scope.row.name">{{ scope.row.name }}</span>
          <span v-else>{{ scope.row.jcZonesDtLabel }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最低收费" align="center" prop="minMoney"/>
      <el-table-column label="方单价" align="center" prop="volumePrices"/>
      <el-table-column label="吨单价" align="center" prop="weightPrices"/>
      <el-table-column label="公里数" align="center" prop="mileage"/>
      <el-table-column label="末端配送时效(小时)" align="center" prop="endShippingTime" width="100"/>
      <el-table-column label="送货费" align="center" prop="deliveryCharge"/>
      <el-table-column label="其他单价" align="center" prop="id">
        <template #default="scope">
          <el-button type="success" @click="handleDelivery(scope.row)" size = "mini">其他单价表</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['extend:serverZone:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['extend:serverZone:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改服务区域对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="服务区域" prop="jcZoneArray">
          <el-cascader :props="regionProps" v-model="form.jcZoneArray" style="width: 100%;"></el-cascader>
        </el-form-item>
        <el-form-item label="最低收费" prop="minMoney">
          <el-input-number size="mini" :min="0" v-model="form.minMoney" placeholder="请输入最低收费"/>
        </el-form-item>
        <el-form-item label="方单价" prop="volumePrices">
          <el-input-number size="mini" :min="0" v-model="form.volumePrices" placeholder="请输入方单价"/>
        </el-form-item>
        <el-form-item label="吨单价" prop="weightPrices">
          <el-input-number size="mini" :min="0" v-model="form.weightPrices" placeholder="请输入吨单价"/>
        </el-form-item>
        <el-form-item label="送货费" prop="deliveryCharge">
          <el-input-number size="mini" :min="0" v-model="form.deliveryCharge" placeholder="请输入送货费"/>
        </el-form-item>

        <el-form-item label="公里数" prop="mileage">
          <el-input-number size="mini" :min="0" v-model="form.mileage" placeholder="请输入公里数"/>
        </el-form-item>

        <el-form-item label="末端配送时效(小时)" prop="endShippingTime">
          <el-input-number size="mini" :min="0" v-model="form.endShippingTime" placeholder="请输入末端配送时效"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 其他费用对话框 -->
    <el-dialog :close-on-click-modal="false" :title="otherCostTitle" :visible.sync="otherCostOpen" width="700px" append-to-body>
      <el-form ref="otherCostForm" :model="otherCostForm" :rules="otherCostRules" label-width="90px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="otherCostForm.name" placeholder="请输入名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="费用类型" prop="otherFeeType">
              <el-select clearable filterable v-model="otherCostForm.otherFeeType" placeholder="请选择费用类型">
                <el-option
                  v-for="dict in dict.type.otherFeeType"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="税率" prop="taxRate">
              <el-radio-group v-model="otherCostForm.taxRate">
                <el-radio
                  v-for="dict in dict.type.TaxRate"
                  :key="dict.value"
                  :label="Number(dict.label)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="方单价" prop="volumePrice">
              <el-input-number size="mini" v-model="otherCostForm.volumePrice" placeholder="请输入方单价"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="吨单价" prop="weightPrice">
              <el-input-number size="mini" v-model="otherCostForm.weightPrice" placeholder="请输入吨单价"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div>
        <el-button type="primary" size="mini" @click="submitOtherCostForm">新增保存</el-button>
      </div>
      <el-table :data="otherCostList">
        <el-table-column label="组织" align="center" prop="dtMap.jcOrganizationIdDtLabel"/>
        <el-table-column label="其他费用类型" align="center" prop="otherFeeType">
          <template #default="scope">
            <dict-tag :options="dict.type.OtherFeeType" :value="scope.row.otherFeeType"/>
          </template>
        </el-table-column>
        <el-table-column label="税率" align="center" prop="taxRate">
          <template #default="scope">
            <dict-tag :options="dict.type.TaxRate" :value="scope.row.taxRate"/>
          </template>
        </el-table-column>
        <el-table-column label="方单价" align="center" prop="volumePrice"/>
        <el-table-column label="吨单价" align="center" prop="weightPrice"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleOtherCostDelete(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>


    <!-- 配送费用对话框 -->
    <el-dialog :close-on-click-modal="false" :title="deliveryPriceTitle" :visible.sync="deliveryPriceOpen" width="700px" append-to-body>
      <el-form ref="deliveryForm" :model="deliveryForm" :rules="deliveryRules" label-width="90px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="deliveryForm.name" placeholder="请输入名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单价" prop="price">
              <el-input-number size="mini" v-model="deliveryForm.price" placeholder="请输入单价"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区间类型" prop="zlInterval">
              <el-select clearable filterable v-model="deliveryForm.zlInterval" placeholder="请选择区间类型">
                <el-option
                  v-for="dict in dict.type.zlinterval"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div>
        <el-button type="primary" size="mini" @click="submitDeliveryForm">新增保存</el-button>
      </div>
      <el-table :data="deliveryPriceList">
        <el-table-column label="名称" align="center" prop="name"/>
        <el-table-column label="区间" align="center" prop="zlInterval">
          <template #default="scope">
            <dict-tag :options="dict.type.zlinterval" :value="scope.row.zlInterval"/>
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center" prop="price"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeliveryDelete(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>


    <!-- 导入对话框 -->
    <el-dialog :close-on-click-modal="false" :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入从列表中导出的xlsx格式文件，请修改对应数据后再导入</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addServerZone, delServerZone, getServerZone, listServerZone, updateServerZone } from '@/api/extend/serverZone'
import { getChildZone } from '@/api/kysys/zone'
import { addDeliveryPrice, delDeliveryPrice, listDeliveryPrice } from '@/api/fee/deliveryPrice'
import { delOtherCost, listOtherCost } from '@/api/fee/otherCost'
import { getToken } from '@/utils/auth'

export default {
  name: 'ServerZone',
  dicts: ['serviceType', 'OtherFeeType', 'zlinterval', 'TaxRate'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 服务区域表格数据
      serverZoneList: [],

      // 弹出层标题
      deliveryPriceTitle: '',
      // 是否显示弹出层
      deliveryPriceOpen: false,
      deliveryForm: {},
      // 服务区域其他单价表格数据
      deliveryPriceList: [],
      deliveryRules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "单价不能为空", trigger: "blur" }
        ],
        zlInterval: [
          { required: true, message: "区间不能为空", trigger: "blur" }
        ],
      },
      // 弹出层标题
      otherCostTitle: '',
      // 是否显示弹出层
      otherCostOpen: false,
      otherCostForm: {},
      // 服务区域其他单价表格数据
      otherCostList: [],
      otherCostRules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        otherFeeType: [
          { required: true, message: "费用类型不能为空", trigger: "change" }
        ],
        taxRate: [
          { required: true, message: "税率不能为空", trigger: "blur" }
        ]
      },
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
        type: null,
        jcZoneId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        jcZoneArray: [
          { required: true, message: '服务区域不能为空', trigger: 'blur' }
        ]
      },
      regionProps: {
        lazy: true,
        lazyLoad(node, resolve) {
          let zid = node.value || 0
          getChildZone({zid: zid}).then(response => {
            resolve(response.data)
          })

        },
        multiple: true,
        checkStrictly: true,
        value: 'id',
        label: 'name'
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/extend/serverZone/importData'
      },
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询服务区域列表 */
    getList() {
      this.loading = true
      listServerZone(this.queryParams).then(response => {
        this.serverZoneList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createName: null,
        createTime: null,
        description: null,
        modifyName: null,
        modifyTime: null,
        name: null,
        status: null,
        type: null,
        jcZoneId: null,
        jcZoneArray: [],
        jcZones: null,
        minMoney: null,
        volumePrices: null,
        weightPrices: null,
        mileage: null,
        endShippingTime: null,
        deliveryCharge: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.regionProps.multiple = true
      this.open = true
      this.title = '添加服务区域'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getServerZone(id).then(response => {
        this.form = response.data
        if (this.form.jcZones) {
          this.form.jcZoneArray = this.form.jcZones.split(',').map(Number)
        }
        this.regionProps.multiple = false
        this.open = true
        this.title = '修改服务区域'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            if (this.form.jcZoneArray) {
              this.form.jcZones = this.form.jcZoneArray.join(',')
            }
            updateServerZone(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            if (this.form.jcZoneArray) {
              this.form.jcZones = ''
              this.form.jcZoneIds = ''
              this.form.jcZoneArray.map(item => {
                this.form.jcZoneIds += item[item.length - 1] + '-'
                this.form.jcZones += item.toString() + '-'
              })
              console.log(this.form.jcZones)
            }
            addServerZone(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除服务区域编号为"' + ids + '"的数据项？').then(function() {
        return delServerZone(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('extend/serverZone/export', {
        ...this.queryParams
      }, `serverZone_${new Date().getTime()}.xlsx`)
    },

    /** 新增按钮操作 */
    handleOtherCost() {
      this.otherCostOpen = true
      this.otherCostTitle = '其他费用(单价表)'
      this.getOtherCostList()
    },
    /** 新增按钮操作 */
    handleShippingTime() {
      this.$router.push('/timeLiness/index')
    },
    /** 查询其他费用登记列表 */
    getOtherCostList() {
      listOtherCost({}).then(response => {
        this.otherCostList = response.data
      })
    },
    /** 提交按钮 */
    submitOtherCostForm() {
      this.$refs['otherCostForm'].validate(valid => {
        if (valid) {
          addDeliveryPrice(this.otherCostForm).then(response => {
            this.$modal.msgSuccess('新增成功')
            this.resetForm('otherCostForm')
            this.otherCostForm = {}
            this.getOtherCostList()
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleOtherCostDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除其他费用登记编号为"' + ids + '"的数据项？').then(function() {
        return delOtherCost(ids)
      }).then(() => {
        this.getOtherCostList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },

    /** 新增按钮操作 */
    handleDelivery(row) {
      this.deliveryForm.jcServerZoneId = row.id
      this.deliveryPriceOpen = true
      this.deliveryPriceTitle = '服务区域其他单价'
      this.getDeliveryList()
    },
    getDeliveryList() {
      listDeliveryPrice({ jcServerZoneId: this.deliveryForm.jcServerZoneId }).then(response => {
        this.deliveryPriceList = response.data
      })
    },
    /** 提交按钮 */
    submitDeliveryForm() {
      this.$refs['deliveryForm'].validate(valid => {
        if (valid) {
          addDeliveryPrice(this.deliveryForm).then(response => {
            this.$modal.msgSuccess('新增成功')
            this.resetForm('deliveryForm')
            this.deliveryForm = {}
            this.getDeliveryList()
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDeliveryDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除服务区域其他单价编号为"' + ids + '"的数据项？').then(function() {
        return delDeliveryPrice(ids)
      }).then(() => {
        this.getDeliveryList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '导入配送时效数据'
      this.upload.open = true
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert('<div style=\'overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;\'>' + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
  }
}
</script>
